// ManualBot.cpp : Defines the entry point for the console application.
//

#define _CRT_SECURE_NO_DEPRECATE 1
#include "stdafx.h"
#include "Grapher.h"
#include "Graph.h"
#include "AStarSearch.h"
#include "MultiAgent.h"
#include "FollowSearchPathState.h"

#include <conio.h>   //for getch(), needed in wait_for_key()
#include <windows.h> //for Sleep()
void sleep(int i) { Sleep(i*1000); }
long GetTime();
void process_args(int argc, char* argv[]);

int _tmain(int argc, char* argv[])
{
	process_args(argc, argv);

	BZRC* remote = Remote::instance();
	World* world = World::instance();

	AStarSearch as;

	vector<constant_t> constants;

	int granularity = 8;
	Graph g(granularity);
	g.buildEdges();
	Vector2 start, goal;

	start.x =  world->flags()[3].pos[0];
	start.y =  world->flags()[3].pos[1];

	goal.x = world->flags()[2].pos[0];
	goal.y = world->flags()[2].pos[1];

	//Grapher gr("test.gpi");
	//as.displaySearch(g, start, goal, gr, true, 10, false, "astar.gpi", Vector2(-200, 0), Vector2(-100, 100), 3000);
	//as.displaySearch(g, start, goal, gr, true, 100, true, "astar2.gpi", Vector2(-400, -100), Vector2(-150, 150));

	std::vector<MultiAgent> agents;
	for(unsigned int i = 0; i < world->tanks().size(); i ++){
		agents.push_back(MultiAgent(&world->tanks()[i]));
	}

	for(unsigned int i = 0; i < agents.size(); i ++){
		agents.at(i).setState(new FollowSearchPathState(&g, Vector2(world->tanks()[i].pos[0],world->tanks()[i].pos[1]), goal, true));
	}

	vector<Command> commands;

	while (true) {
		long t1 = GetTime();

		// First update our understanding of the world
		// and send all commands.
		world->update(commands);
		commands.clear();

		// Then have our team react to that knowledge
		for(unsigned int i = 0; i < agents.size(); i ++){
			//commands.push_back(agents[i].GetCommand());
		}

		long t2 = GetTime();

		cout << "Loop Time: " << t2 - t1 << "ms" << endl;
	}

	return 0;
}

void process_args(int argc, char* argv[]) {
	string server;
	int port;

	if(argc < 2) {
		cout << "server: ";
		cin >> server;
	}
	else {
		server = argv[1];
	}
    if(argc < 3) {
		cout << "port: ";
		cin >> port;
	}
	else {
        port = atoi(argv[2]);
    }

	Remote::init(server, port, false);

	if (!Remote::instance()->GetStatus()) {
		cout << "Unable to contact server" << endl;
		exit(1);
	}
}

long GetTime() {
	SYSTEMTIME tm;
	GetSystemTime(&tm);
	return (long)tm.wMilliseconds + 
		   (long)tm.wSecond * 1000 + 
		   (long)tm.wMinute * 60000 + 
		   (long)tm.wHour * 3600000;// + 
		   //(long)tm.wDay * 86400000;
}